package com.project.controller.web;

import com.alibaba.fastjson.JSON;
import com.project.myBeans.R;
import com.project.myBeans.ResponseBean;
import com.project.service.base.BaseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * @Author: TateBrown
 * @date: 2018/5/27 16:07
 * @param:
 * @return:
 */
@EnableAutoConfiguration //自动载入应用程序所需的所有Bean
@RestController //@Controller与@ResponseBody的合并
@RequestMapping(value = "/Public")
@Api(description = "文件上传控制",value = "public")
public class PublicController  extends BaseService {
    /**
     * TateBrown 2018年5月27日
     *
     * @param file
     * @return
     */
    @ApiOperation(" 文件上传")
    @PostMapping("/fileUpload")
    public R upload(@RequestParam("fileUp") CommonsMultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //System.out.println("File!!++++++++++");
        ResponseBean responseBean = new ResponseBean();
        try {
            String savePath = request.getSession().getServletContext().getRealPath("/WEB-INF/static/upload");
            //多级地创建目录
            File f1 = new File(savePath);
            if (!f1.exists()) f1.mkdirs();


            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();


//            上传文件在服务器的文件名
            String fileName = "";


            file.getFileItem().getName();
//            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
//                MultipartFile file = entity.getValue();
//                if (file.isEmpty()) continue;
//        }

//            获取文件格式
            String name = file.getOriginalFilename();
            //System.out.println("File:"+name);
            String ext = name.substring(name.lastIndexOf('.'));

//            保存到服务器后的新文件名
            fileName = new Date().getTime() + ext;

//            创建文件保存对象
            File f = new File(savePath + "/" + fileName);

//            获取文件输出流
            FileOutputStream out = new FileOutputStream(f);

//            保存文件
            FileCopyUtils.copy(file.getInputStream(), out);

            System.out.println(fileName);


            return R.ok().put("data",fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error();
        }
    }

}


/*@RestController
@RequestMapping("/upload")
@CrossOrigin
public class UploadController {
    @Value("${prop.upload-folder}")
    private String UPLOAD_FOLDER;
    private  Logger logger = LoggerFactory.getLogger(UploadController.class);

    @PostMapping("/singlefile")
    public Object singleFileUpload(MultipartFile file) {
        logger.debug("传入的文件参数：{}", JSON.toJSONString(file, true));
        if (Objects.isNull(file) || file.isEmpty()) {
            logger.error("文件为空");
            return "文件为空，请重新上传";
        }
        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOAD_FOLDER + file.getOriginalFilename());
            //如果没有files文件夹，则创建
            if (!Files.isWritable(path)) {
                Files.createDirectories(Paths.get(UPLOAD_FOLDER));
            }
            //文件写入指定路径
            Files.write(path, bytes);
            logger.debug("文件写入成功...");
            return "文件上传成功";
        } catch (IOException e) {
            e.printStackTrace();
            return "后端异常...";
        }

    }
}*/
